<template>
    <div style="width:100%;" ref="refTop">
        <slot></slot>
    </div>
</template>

<script lang="ts" setup>
import { ref, onMounted, Ref, withDefaults } from 'vue'


const props = withDefaults(defineProps<{cardClass:string, dropwidth?:number|null}>(), {
    dropwidth: null ,
    cardClass: "card-item"
})

const refTop = ref(null) as unknown as Ref<HTMLElement>

const emit = defineEmits([
    "card-drag-start",
    "card-drag-out",
    "card-dragging",
    "card-drag-cancel"
])

onMounted ( function() {

    let $self: any = $(refTop.value)

    let minOffsetTop = 0
    let $draggingItem: any
    let stackWidth = 0
    let cancel = true

    $self.draggable({
        scroll: false ,
        refreshPositions: true ,
        start: (e:any) => {
            cancel = true
            $draggingItem = $(e.toElement)
            if(!$draggingItem.hasClass(props.cardClass)) {
                $draggingItem = $draggingItem.parents("."+props.cardClass).eq(0)
            }
            if(!$draggingItem.hasClass(props.cardClass)) {
                $draggingItem = null
            }

            minOffsetTop = $self.parent().height() - $self.height()
            if(minOffsetTop>0) {
                minOffsetTop = 0
            }

            stackWidth = (props.dropwidth==null)? $self.width(): props.dropwidth

            emit("card-drag-start")
        } ,
        drag: (event:any, ui:any)=>{
            if(ui.offset.top > 0) {
                ui.position.top = 0
            }
            if(ui.offset.top < minOffsetTop) {
                ui.position.top = minOffsetTop
            }

            if($draggingItem) {

                $draggingItem.css("margin-left", ui.position.left)

                if(event.clientX>stackWidth) {
                    cancel = false
                    emit('card-drag-out', $draggingItem, event.clientX, event.clientY)
                    return false
                }
            }

            ui.position.left = 0

            emit("card-dragging")
        } ,
        stop: (event:any, ui:any)=>{
            if($draggingItem) {
                $draggingItem.css("margin-left", 0)
                $draggingItem = null
            }
            if(cancel)
                emit("card-drag-cancel")
        }
    })

    // 鼠标滚轮
    $self.on('mousewheel', (event: any) => {
        
        let top = $self.position().top
        top+= event.deltaY * 50

        if(top>=0) {
            top = 0
        }
        let minTop = $self.parent().innerHeight() - $self.outerHeight()
        if(minTop>0)
            minTop = 0
        if( top<minTop )
            top = minTop

        $self.css('top', top)
    });
})

</script>